<template>
	<view class="addpatient">
		<view class="inps">
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field v-model="name" name="name" label="就诊人姓名" placeholder="就诊人姓名"
						:rules="[{ required: true, message: '请填写就诊人姓名' }]" />
						<van-field v-model="idNumber" name="idNumber" label="身份证号码" @input="getage" placeholder="身份证号码" :rules="[{ required: true, message: '请填写就诊人身份证号码' }]" />
					<van-field v-model="sex" name="sex" readonly label="就诊人性别" placeholder="就诊人性别"
						:rules="[{ required: true, message: '请填写就诊人性别' }]" />
					
					<van-field v-model="age" name="age" readonly label="年龄" placeholder="就诊人年龄"
						:rules="[{ required: true, message: '请填写就诊人年龄' }]" />


				</van-cell-group>
				<van-button class="btn" block type="primary" native-type="submit" size="normal">
					确定
				</van-button>
			</van-form>
		</view>

	</view>
</template>

<script setup>
	import {ref,onBeforeMount} from 'vue'
	import api from '../../lib/request.js'
	import {
		showToast
	} from 'vant';
	const name = ref('');
	const sex = ref('');
	const age = ref('');
	const idNumber = ref('')
	const getage = () => {
		let realage = idNumber.value.substr(6, 4)
		age.value = new Date().getFullYear() - realage
		// 判断男女
		switch (idNumber.value.length) {
			// 一代长度
			case 15:
				// 根据第15位数判断,男基女偶数
				let s = idNumber.value.substr(14, 1)
				sex.value = (s % 2) ? '男' : '女'
				break;
				// 二代长度,	// 根据第17位数判断,男基女偶数
			case 18:
				let e = idNumber.value.substr(16, 1)
				sex.value = (e % 2) ? '男' : '女'
				break;
		}
	}
	const onSubmit = (values) => {
		let regex = /^[1-9]\d{5}(19|20)\d{2}(0\d|1[0-2])([0-2]\d|3[0-1])\d{3}([0-9]|X)$/
		console.log(regex.test(idNumber.value))
		if (!regex.test(idNumber.value)) {
			showToast('身份证格式不正确')
			idNumber.value = ''
			return
		}
		api.post('/user/patient', values).then(res => {
			console.log(res)
			if(res.code){
				showToast('添加成功')
				setTimeout(()=>{uni.redirectTo(
				{
					url:'/views/allpatient/allpatient'
				}) },1500)
			}
		})
	}
</script>

<style lang="scss" scoped>
	.inps {
		margin-top: 10px;
	}

	.btn {
		position: fixed;
		bottom: 0;
		font-size: 16px;
	}
</style>